/*******************************************************************************
 * Copyright 2013 Fsoftvn (kelvin)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package arisufascion.com.network;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.util.Log;
import arisufascion.com.constant.Constants;
import arisufascion.com.constant.WriteLog;
import arisufascion.com.model.Profile;

/**
 * @author kelvin
 * 
 */
public class RequestTask {

	public static String getJsonFromUrl(String url) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response;
		String responseString = null;
		try {
			response = httpclient.execute(new HttpGet(url));
			StatusLine statusLine = response.getStatusLine();
			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				response.getEntity().writeTo(out);
				out.close();
				responseString = out.toString();
			} else {
				// Closes the connection.
				response.getEntity().getContent().close();
				throw new IOException(statusLine.getReasonPhrase());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			Log.d("Kelvin", e.getMessage());
		} catch (IOException e) {

			Log.d("Kelvin", e.getMessage());
			e.printStackTrace();
		}
		return responseString;
	}

	public static String getJsonString(String url) {
		StringBuilder result = null;
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);
		HttpResponse response = null;
		try {
			response = httpclient.execute(httpget);

			HttpEntity entity = response.getEntity();
			result = new StringBuilder(EntityUtils.toString(entity));
			return result.toString();

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * Convert stream to string.
	 * 
	 * @param is
	 *            the is
	 * @return the string
	 */
	private static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	/**
	 * Making service call
	 * 
	 * @url - url to make request
	 * @method - http request method
	 * @params - http request params
	 * */
	public static String makeServiceCall(String url) {
		String response = null;
		try {
			// http client
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpEntity httpEntity = null;
			HttpResponse httpResponse = null;

			// appending params to url
			HttpGet httpGet = new HttpGet(url);

			httpResponse = httpClient.execute(httpGet);

			httpEntity = httpResponse.getEntity();
			response = EntityUtils.toString(httpEntity);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return response;

	}

	public static String checkLogin(Context c, String username, String password) {
		// send registryId to server php
		String urlProfile = Constants.SERVER_URL_LOGIN;

		try {
			// Add parent data
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(urlProfile);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);

			nameValuePairs.add(new BasicNameValuePair("username", username));
			nameValuePairs.add(new BasicNameValuePair("password", password));
			nameValuePairs.add(new BasicNameValuePair("key",
					Constants.SERVER_API_KEY));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();

			return line;
			// WriteLog.d("Kelvin Login", line);

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		return null;

	}

	public static String creatAccount(Context c, Profile account) {
		// send registryId to server php
		String urlProfile = Constants.SERVER_URL_CREATE_ACCOUNT;

		try {
			// Add parent data
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(urlProfile);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
					21);

			nameValuePairs.add(new BasicNameValuePair("username", account
					.getUsername()));
			nameValuePairs.add(new BasicNameValuePair("password", account
					.getPassword()));
			nameValuePairs.add(new BasicNameValuePair("password2", account
					.getPassword()));
			nameValuePairs.add(new BasicNameValuePair("title", account
					.getTitle()));
			nameValuePairs.add(new BasicNameValuePair("first_name", account
					.getFirst_name()));
			nameValuePairs.add(new BasicNameValuePair("middle_name", account
					.getMiddle_name()));
			nameValuePairs.add(new BasicNameValuePair("last_name", account
					.getLast_name()));
			nameValuePairs.add(new BasicNameValuePair("phone_1", account
					.getPhone_1()));
			nameValuePairs.add(new BasicNameValuePair("phone_2", account
					.getPhone_2()));
			nameValuePairs.add(new BasicNameValuePair("fax", account.getFax()));
			nameValuePairs.add(new BasicNameValuePair("address_1", account
					.getAddress_1()));
			nameValuePairs.add(new BasicNameValuePair("address_2", account
					.getAddress_2()));
			nameValuePairs
					.add(new BasicNameValuePair("city", account.getCity()));
			nameValuePairs.add(new BasicNameValuePair("country_id", account
					.getCountry_id()));
			nameValuePairs.add(new BasicNameValuePair("state_id", account
					.getState_id()));
			nameValuePairs.add(new BasicNameValuePair("zip", account.getZip()));
			nameValuePairs
					.add(new BasicNameValuePair("name", account.getName()));
			nameValuePairs.add(new BasicNameValuePair("email", account
					.getEmail()));
			nameValuePairs.add(new BasicNameValuePair("company", account
					.getCompany()));

			nameValuePairs.add(new BasicNameValuePair("key",
					Constants.SERVER_API_KEY));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();

			return line;
			// WriteLog.d("Kelvin Login", line);

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		return null;

	}

	public static String saveOrder(Context c, Profile account,
			String color_ids, String size_ids, String product_ids,
			String product_quantitys,String customer_note) {
		// send registryId to server php
		String url = Constants.SERVER_URL_ORDER;

		try {
			// Add parent data
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
					40);

			nameValuePairs
					.add(new BasicNameValuePair("colorid_list", color_ids));
			nameValuePairs.add(new BasicNameValuePair("sizeid_list", size_ids));
			nameValuePairs.add(new BasicNameValuePair("id_pro_list",
					product_ids));
			nameValuePairs.add(new BasicNameValuePair("quatity_pro_list",
					product_quantitys));
			nameValuePairs.add(new BasicNameValuePair("customer_note",
					customer_note));
			nameValuePairs.add(new BasicNameValuePair("userid", String
					.valueOf(account.getId())));

			// set data for billing order
			// URLEncoder.encode(
			nameValuePairs.add(new BasicNameValuePair("b_company", URLEncoder
					.encode(account.getCompany_name(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("b_title", URLEncoder
					.encode(account.getTitle(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("b_last_name", URLEncoder
					.encode(account.getLast_name(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("b_first_name",
					URLEncoder.encode(account.getFirst_name(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("b_middle_name",
					URLEncoder.encode(account.getMiddle_name(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("b_phone_1", URLEncoder
					.encode(account.getPhone_1(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("b_phone_2", URLEncoder
					.encode(account.getPhone_2(), "UTF-8")));
			nameValuePairs
					.add(new BasicNameValuePair("b_fax", account.getFax()));
			nameValuePairs.add(new BasicNameValuePair("b_address_1", URLEncoder
					.encode(account.getAddress_1(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("b_address_2", URLEncoder
					.encode(account.getAddress_2(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("b_city", URLEncoder
					.encode(account.getCity(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("b_state_id", account
					.getState_id()));
			nameValuePairs.add(new BasicNameValuePair("b_country_id", account
					.getCountry_id()));
			nameValuePairs.add(new BasicNameValuePair("b_zip", URLEncoder
					.encode(account.getZip(), "UTF-8")));
			
			nameValuePairs.add(new BasicNameValuePair("b_email", account
					.getEmail()));

			// set data for Shipping order
			nameValuePairs.add(new BasicNameValuePair("s_company", URLEncoder
					.encode(account.getCompany_name(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("s_title", URLEncoder
					.encode(account.getTitle(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("s_last_name", URLEncoder
					.encode(account.getLast_name(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("s_first_name",
					URLEncoder.encode(account.getFirst_name(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("s_middle_name",
					URLEncoder.encode(account.getMiddle_name(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("s_phone_1", URLEncoder
					.encode(account.getPhone_1(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("s_phone_2", URLEncoder
					.encode(account.getPhone_2(), "UTF-8")));
			nameValuePairs
					.add(new BasicNameValuePair("s_fax", account.getFax()));
			nameValuePairs.add(new BasicNameValuePair("s_address_1", URLEncoder
					.encode(account.getAddress_1(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("s_address_2", URLEncoder
					.encode(account.getAddress_2(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("s_city", URLEncoder
					.encode(account.getCity(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("s_state_id", account
					.getState_id()));
			nameValuePairs.add(new BasicNameValuePair("s_country_id", account
					.getCountry_id()));
			nameValuePairs.add(new BasicNameValuePair("s_zip", URLEncoder
					.encode(account.getZip(), "UTF-8")));
			nameValuePairs.add(new BasicNameValuePair("s_email", account
					.getEmail()));

			nameValuePairs.add(new BasicNameValuePair("key",
					Constants.SERVER_API_KEY));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();

			WriteLog.d("Kelvin create account", line);

			return line;

		} catch (ClientProtocolException e) {

			WriteLog.d("Kelvin Order Insert", e.getMessage());

		} catch (IOException e) {
			WriteLog.d("Kelvin Order Insert", e.getMessage());
		}
		return null;

	}
	
	public static String updateOrder(Context c, String status) {
		// send registryId to server php
		String url = Constants.SERVER_URL_UPDATE_ORDER;

		try {
			// Add parent data
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
					2);

			nameValuePairs
					.add(new BasicNameValuePair("status", status));

			nameValuePairs.add(new BasicNameValuePair("key",
					Constants.SERVER_API_KEY));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();

			WriteLog.d("Kelvin update order", line);

			return line;

		} catch (ClientProtocolException e) {

			WriteLog.d("Kelvin Order update", e.getMessage());

		} catch (IOException e) {
			WriteLog.d("Kelvin Order update", e.getMessage());
		}
		return null;

	}
	

	public static String createContact(Context c, String name, String email,
			String contact, String subject, String message) {
		// send registryId to server php
		String urlProfile = Constants.SERVER_URL_CREATE_CONTACT;

		try {
			// Add parent data
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(urlProfile);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);

			nameValuePairs.add(new BasicNameValuePair("fullName", name));
			nameValuePairs.add(new BasicNameValuePair("email", email));
			nameValuePairs.add(new BasicNameValuePair("contact", contact));
			nameValuePairs.add(new BasicNameValuePair("subject", subject));
			nameValuePairs.add(new BasicNameValuePair("message", message));
			nameValuePairs.add(new BasicNameValuePair("key",
					Constants.SERVER_API_KEY));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();
			WriteLog.d("Kelvin Login", line);
			return line;

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		return null;

	}

	public static String createEmail(Context c,  String email) {
		// send registryId to server php
		String urlProfile = Constants.SERVER_URL_CREATE_EMAIL;

		try {
			// Add parent data
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(urlProfile);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);

			nameValuePairs.add(new BasicNameValuePair("email", email));
			
			nameValuePairs.add(new BasicNameValuePair("key",Constants.SERVER_API_KEY));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();
			
			WriteLog.d("Kelvin emailing list", line);
			
			return line;

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		return null;

	}
	
	public static String forGotPassword(Context c,  String email) {
		// send registryId to server php
		String urlProfile = Constants.SERVER_URL_FOR_GOT_PASSWORD;

		try {
			// Add parent data
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(urlProfile);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);

			nameValuePairs.add(new BasicNameValuePair("email", email));
			
			nameValuePairs.add(new BasicNameValuePair("key",Constants.SERVER_API_KEY));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();
			
			WriteLog.d("Kelvin email for got password", line);
			
			return line;

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		return null;

	}
	
	
}
